// 消息总线
import 'dart:async';
import 'package:demo/tools/tools_enum.dart';
import 'package:demo/tools/tools_sqlite.dart';
import 'package:demo/tools/tools_storage.dart';

// 监听聊天消息
class EventMessage {
  EventMessage._();
  static EventMessage? _singleton;
  factory EventMessage() => _singleton ??= EventMessage._();
  // 消息
  final StreamController<ChatMsg> listenMsg = StreamController.broadcast();
  // 历史
  final StreamController<ChatHis> listenHis = StreamController.broadcast();
  // 发送
  final StreamController<EventChatModel> listenSend =
      StreamController.broadcast();

  // 监听聊天消息
  addListen() {
    return listenSend.stream.listen((chatModel) async {
      // 聊天对象
      LocalChat localChat = chatModel.chat;
      // 消息类型
      MsgType msgType = chatModel.msgType;
      // 聊天对象
      LocalUser localUser = ToolsStorage().local();
      // 消息内容
      Map<String, dynamic> content = chatModel.content;
      Map<String, dynamic> source = {
        'userId': localUser.userId,
        'nickname': localUser.nickname,
        'portrait': localUser.portrait,
      };
      // 消息ID
      String msgId = DateTime.now().microsecondsSinceEpoch.toString();
      // 组装消息
      ChatHis chatHis = ChatHis(
        msgId,
        localChat.chatId,
        localChat.portrait,
        localChat.title,
        source,
        msgType,
        content,
        localChat.chatTalk,
        DateTime.now(),
      );
      // 存储消息
      await ToolsSqlite().his.add(chatHis);
      // 广播消息
      listenHis.add(chatHis);
      // 组装消息
      ChatMsg chatMsg = ChatMsg(
        localChat.chatId,
        localChat.title,
        localChat.portrait,
        msgId,
        msgType,
        content,
        localChat.chatTalk,
        DateTime.now(),
      );
      // 存储消息
      await ToolsSqlite().msg.add(chatMsg);
      // 广播消息
      listenMsg.add(chatMsg);
    });
  }
}

// 扩展对象
class EventChatModel {
  // 接收对象
  LocalChat chat;
  // 消息类型
  MsgType msgType;
  // 消息内容
  Map<String, dynamic> content;

  EventChatModel(
    this.chat,
    this.msgType,
    this.content,
  );
}
